from rest_framework import serializers
from private_website.apps.app01 import models
from tools.const import BASE_DIR
import os


class SFavoriteSer(serializers.Serializer):
    id = serializers.CharField()
    name = serializers.CharField()
    cover = serializers.CharField()

    def validated_cover(self, data):
        path = BASE_DIR + data
        try:
            os.open(path, flags=0)
        except Exception:
            models.SFavorites.objects.filter(id=self.id).update(cover='/static/default.png')
        return data


class SFavoriteInfoSer(serializers.Serializer):
    id = serializers.CharField()
    name = serializers.CharField()
    cover = serializers.CharField()


class ImageSer(serializers.ModelSerializer):
    class Meta:
        model = models.Image
        fields = ['path', 'favorite']


class FavoriteSer(object):
    def __init__(self, obj, method=None, favorite=None):
        self.data = []
        if method == '-1':
            for i in obj:
                self.data.append({'type': 'L', 'value': i.id, 'label': i.name})
                m_obj = models.MFavorites.objects.filter(favorite=i).all()
                self.data[-1]['children'] = []
                for j in m_obj:
                    num = models.SFavorites.objects.filter(favorite=j).count()
                    num = j.name + '(' + str(num) + ')'
                    self.data[-1]['children'].append({'type': 'M', 'value': j.id, 'label': num})
        elif method == '0':
            obj = models.SFavorites.objects.filter(favorite_id=favorite).all()
            self.data = SFavoriteInfoSer(obj, many=True).data
        else:
            for i in obj:
                self.data.append({'type': 'L', 'value': i.id, 'label': i.name})
                m_obj = models.MFavorites.objects.filter(favorite=i).all()
                self.data[-1]['children'] = []
                for j in m_obj:
                    s_obj = models.SFavorites.objects.filter(favorite=j).all()
                    # num = j.name + '(' + str(num) + ')'
                    self.data[-1]['children'].append({'type': 'M', 'value': j.id, 'label': j.name})
                    self.data[-1]['children'][-1]['children'] = []
                    for z in s_obj:
                        self.data[-1]['children'][-1]['children'].append({
                            'type': 'S',
                            'value': z.id,
                            'label': z.name,
                            'cover': z.cover
                        })